package admin

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	"syudy/Models"
)

type AccessController struct {
	BaseController
}

func (con AccessController) Index(c *gin.Context) {
	accessList := []Models.Access{}
	Models.DB.Where("module_id = ?", 0).Preload("AccessList").Find(&accessList)
	c.HTML(http.StatusOK, "admin/access/index.html", gin.H{
		"accessList": accessList,
	})
}

func (con AccessController) Add(c *gin.Context) {
	//获取顶级模块
	accessList := []Models.Access{}
	Models.DB.Where("module_id = ?", 0).Find(&accessList)
	c.HTML(http.StatusOK, "admin/access/add.html", gin.H{
		"accessList": accessList,
	})
}

// 增加角色
func (con AccessController) DoAdd(c *gin.Context) {
	moduleName := strings.Trim(c.PostForm("module_name"), "")
	accessType, err1 := con.StringInt(c.PostForm("type"))
	url := c.PostForm("url")
	moduleId, err2 := con.StringInt(c.PostForm("module_id"))
	sort, err3 := con.StringInt(c.PostForm("sort"))
	description := c.PostForm("description")
	status, err4 := con.StringInt(c.PostForm("status"))
	actionName := c.PostForm("action_name")
	if err1 != nil || err2 != nil || err3 != nil || err4 != nil {
		con.Error(c, "传入参数错误", "/admin/access/add")
	}
	if moduleName == "" {
		con.Error(c, "模块名称不能为空", "/admin/access/add")
	}

	access := Models.Access{
		ModuleName:  moduleName,
		Type:        accessType,
		Url:         url,
		ModuleId:    moduleId,
		Sort:        sort,
		Description: description,
		Status:      status,
		ActionName:  actionName,
	}
	err := Models.DB.Create(&access).Error
	if err != nil {
		con.Error(c, "添加数据失败", "/admin/access/add")
	} else {
		con.Success(c, "添加数据成功", "/admin/access")
	}
}
